package com.czy.ekp.doc;


import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

@Service
public class DocService {



    @Autowired
    JdbcTemplate jdbcTemplate;

    public void toWord(String id, HttpServletResponse response){

        Map<String, Object> article = jdbcTemplate.queryForMap("select * from article where id = ?", new Object[]{id});
        if(article == null){
            try {
                response.getWriter().print("record not exists.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        try {
            String html = article.get("content").toString();
            String name = article.get("title").toString() + ".doc";

            XWPFDocument doc = new DocUtils().html2WordDocument(html);
            response.reset();
//            response.setContentLength(out.length);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name));

            doc.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }






}
